<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\DAO\DepartmentDAO as DeptDao;

class DepartmentController extends Controller
{
    public function __construct()
    {
        $this->middleware("auth:api");
    }

    public function getAll(){
        $all = DeptDAO::getAll();
        return response()->json($all,200);
    }

    public function create(Request $req){
        $data = $req->validate([
            'name' => "required|min:5",
            'address' => "required",
            'telephone' => "required"
        ]);
        $dept = DeptDAO::create($data);
        if($dept){
            return response()->json($dept,200);
        }
        return response()->json(["message"=>"创建部门失败！"],401);
    }

    public function getOne(Request $req, $id){
        $dept = DeptDAO::getOne($id);
        if($dept){
            return response()->json($dept,200);
        }
        return response()->json(["message"=>"Can't find the specified department."],401);
    }

    public function modify(Request $req, $id){
        $data = $req->all();

        $dept = DeptDAO::modify($id,$data);
        if($dept){
            return response()->json($dept,200);
        }
        return response()->json(["message"=>"Modify the specified department failed."],401);
    }

    public function delete($id){
        $dept = DeptDAO::getOne($id);
        if(!$dept){
            return response()->json(["message"=>"指定的部门不存在！"],401);
        }
        $count = DeptDAO::delete($id);
        if($count){
            return response()->json(["message"=>"部门已经删除！","department"=>$dept],200);
        }
        return response()->json(["message"=>"删除指定的部门失败！","department"=>$dept],401);
    }
}
